package luminus.origin.utils

import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.BlockFace
import kotlin.math.abs

// bad performance
private val UNSAFE_BLOCKS = setOf(
    Material.LAVA,
    Material.FIRE,
    Material.CAMPFIRE,
    Material.SOUL_CAMPFIRE,
    Material.MAGMA_BLOCK,
    Material.CACTUS,
    Material.END_PORTAL,
    Material.NETHER_PORTAL
)

private val DANGEROUS_FLUIDS = setOf(
    Material.LAVA,
    Material.WATER
)

fun Location.isSafeLocation(checkSurrounding: Boolean = true): Boolean {
    val world = this.world ?: return false

    if (this.y < world.minHeight || this.y >= world.maxHeight) {
        return false
    }

    val x = this.x
    val y = this.y
    val z = this.z

    val feetBlock = this.block
    val headBlock = feetBlock.getRelative(BlockFace.UP)
    val groundBlock = feetBlock.getRelative(BlockFace.DOWN)

    if (!groundBlock.type.isSolid) {
        return false
    }

    if (UNSAFE_BLOCKS.contains(groundBlock.type)) {
        return false
    }

    if (headBlock.type.isSolid) {
        return false
    }

    if (UNSAFE_BLOCKS.contains(feetBlock.type)) {
        return false
    }

    if (DANGEROUS_FLUIDS.contains(feetBlock.type)) {
        return false
    }

    if (checkSurrounding) {
        for (dx in -1..1) {
            for (dz in -1..1) {
                if (dx == 0 && dz == 0) continue

                val nearbyBlock = world.getBlockAt((x + dx).toInt(), y.toInt(), (z + dz).toInt())
                if (UNSAFE_BLOCKS.contains(nearbyBlock.type) || DANGEROUS_FLUIDS.contains(nearbyBlock.type)) {
                    return false
                }
            }
        }
    }
    if (!hasSolidGround()) {
        return false
    }

    return true
}

fun Location.findNearestSafeLocation(radius: Int = 5): Location? {
    if (isSafeLocation()) {
        return this
    }

    for (r in 1..radius) {
        for (x in -r..r) {
            for (z in -r..r) {
                if (abs(x) != r && abs(z) != r) continue

                for (y in -3..3) {
                    val testLoc = this.clone().add(x.toDouble(), y.toDouble(), z.toDouble())
                    if (testLoc.isSafeLocation()) {
                        return testLoc
                    }
                }
            }
        }
    }

    return null
}

private fun Location.hasSolidGround(depth: Int = 5): Boolean {
    val world = this.world ?: return false
    var y = this.y - 1

    for (i in 0 until depth) {
        if (y < world.minHeight) {
            return false
        }

        val block = world.getBlockAt(this.x.toInt(), y.toInt(), this.z.toInt())
        if (block.type.isSolid) {
            return true
        }

        y--
    }

    return false
}